import loanApi from '@/api/modules/loan';
import { useLoanStore } from '@/store';

/**
 * 贷款服务 - 处理贷款相关的业务逻辑和API调用
 */
class LoanService {
  constructor() {
    this.loanStore = useLoanStore();
  }

  /**
   * 申请贷款
   * @param {Object} loanData 贷款数据
   * @returns {Promise<Object>} 申请结果
   */
  async applyLoan(loanData) {
    try {
      const response = await loanApi.apply(loanData);
      return response;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取用户贷款列表
   * @param {Number} userId 用户ID
   * @returns {Promise<Array>} 贷款列表
   */
  async getLoanList(userId) {
    try {
      const response = await loanApi.getList(userId);
      this.loanStore.setLoans(response);
      return response;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取贷款详情
   * @param {Number} id 贷款ID
   * @returns {Promise<Object>} 贷款详情
   */
  async getLoanDetail(id) {
    try {
      const response = await loanApi.getDetail(id);
      return response;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 取消贷款申请
   * @param {Number} id 贷款ID
   * @returns {Promise<Boolean>} 是否成功
   */
  async cancelLoan(id) {
    try {
      const response = await loanApi.cancel(id);
      return true;
    } catch (error) {
      throw error;
    }
  }
}

// 导出单例
export default new LoanService();